package com.yonyou.pmclouds.plan.processor;

import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.plan.entity.ScheduleVO;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleQueryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Description:
 * @Author: zhangzhonghao
 * @Date: 2020-03-08
 */
@Component
public class ScheduleAdjustBeforeProcessor implements SingleProcessor<ScheduleVO> {

    @Autowired
    private IScheduleQueryService scheduleQueryService;

    @Override
    public void process(ScheduleVO vo, ScheduleVO orig) throws BusinessException {

        checkValue(vo);

        vo.setPkSchedule(UUID.randomUUID().toString());
        vo.setSeq(getSeq(vo.getPkProject()));
        vo.setVersion(vo.getVersion() + 1);
        vo.setBillstatus(BillStatusConst.COMMON_FREE_STATUS);
        vo.setLastFlag("Y");
    }

    private int getSeq(String pkProject) throws BusinessException {
        return scheduleQueryService.queryCountByPkProject(pkProject);
    }

    private void checkValue(ScheduleVO scheduleVO) throws BusinessException {
        ScheduleVO result = scheduleQueryService.queryById(scheduleVO.getOldPkSchedule());
        String creator = RuntimeEnvironment.getLoginUserId();

        if(result == null){
            throw new BusinessException("未找到该计划，请检查数据!");
        }
        if (result.getCreator() == null || !creator.equals(result.getCreator())) {
            throw new BusinessException("当前用户不是该根计划的创建人，不可操作！");
        }

        if(StringUtils.isEmpty(scheduleVO.getName())){
            throw new BusinessException("计划名称不允许为空！");
        }

        if(StringUtils.isBlank(scheduleVO.getPkProject())){
            throw new BusinessException("项目不能为空！");
        }
    }
}
